import { useRef, useState, useEffect } from 'react'
import style from "./socket.module.css";
import { Collapse } from 'antd';
import type { CollapseProps } from 'antd';
import { io, Socket } from 'socket.io-client';
import chat from "/src/assets/logo/chat.png";
import { message, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import type { UploadProps } from 'antd';
import { Popover } from 'antd';
import "./index.css";
import { MinusOutlined, SmileOutlined, FolderAddOutlined, ScissorOutlined, LikeOutlined } from '@ant-design/icons';
// interface Response {
//   user: string;
//   apply: string;
//   time: string;
// }
//
function Index({ handlefan, bool }: { handlefan: () => void; bool: boolean }) {
  // console.log(bool);
  //连接
  // const ws = new WebSocket('ws://localhost:8080'); // 替换为你的 WebSocket 地址
  const socketRef = useRef<Socket | null>(null)  //保持连接的状态
  //
  const messagesRef = useRef<HTMLDivElement | null>(null);
  const scrollToBottom = () => {
    if (messagesRef.current) {
      messagesRef.current.scrollTop = messagesRef.current.scrollHeight;
    }
  };

  //关闭弹框
  const handlereturn = () => {
    handlefan()
  }
  //下拉
  const items: CollapseProps['items'] = [
    {
      key: '0',
      label: '会员相关问题',
      children: <ul>
        {['会员购买咨询咨询', '如何申领购买优惠？'].map((item, index) => (
          <li key={index} onClick={() => handleQuestionClick(item)}><span>{item}</span></li>
        ))}
      </ul>,
    },
    {
      key: '1',
      label: '设计下载问题',
      children: <ul>
        {['如何下载设计？', '如何上传自动的图片？'].map((item, index) => (
          <li key={index} onClick={() => handleQuestionClick(item)}><span>{item}</span></li>
        ))}
      </ul>,
    },
    {
      key: '2',
      label: '会员购买问题',
      children: <ul>
        {['苹果小程序怎么购买会员？'].map((item, index) => (
          <li key={index} onClick={() => handleQuestionClick(item)}><span>{item}</span></li>
        ))}
      </ul>,
    },
    {
      key: '3',
      label: '登录、发票问题',
      children: <ul>
        {['如何使用账号密码登录？', '购买会员如何开发票？'].map((item, index) => (
          <li key={index} onClick={() => handleQuestionClick(item)}><span>{item}</span></li>
        ))}
      </ul>,
    },
  ];
  //
  //是否人工服务
  //
  const [message, setMessage] = useState('')
  const [isTransferring, setIsTransferring] = useState(true);
  //时间
  const [time, setTime] = useState(new Date(Date.now()).toLocaleString());
  //问题
  const [response, setResponse] = useState<any[]>([]);
  //返回
  const [apply, setApply] = useState<any[]>([])
  //自动回复
  const handleQuestionClick = (question: string) => {
    const currentTime = new Date(Date.now()).toLocaleString();
    let reply = `关于${question}的问题回答是。。。`;

    switch (question) {
      case '如何下载设计？':
        reply = `关于${question}的问题检查以确保设计无误，点击设计页右上角“下载”，选择下载文件类型，再点击下载按钮，将设计保存为JPG、PNG、GIF或PDF格式的文件`;
        break;
      case '苹果小程序怎么购买会员？':
        reply = `关于${question}的问题您好，可以在苹果应用商城下载创客贴设计app，在创客贴app购买会员的呢。也可以在电脑网页版登陆账号进行购买会员。温馨提示：手机端会员和电脑网页版是通用的哦~`;
        break;
      case '如何使用账号密码登录？':
        reply = `关于${question}的问题您好，首先在创客贴网页中点击“登陆”按钮，然后点击“密码登陆在这里”按照步骤操作既可。`;
        break;
      default:
        break;
    }

    setResponse(prev => [...prev, { user: question, time: currentTime }]);
    setApply(prev => [...prev, { apply: '', time: currentTime }]);

    setTimeout(() => {
      setApply(prev => {
        const newResponses = [...prev];
        newResponses[newResponses.length - 1].apply = reply; // 更新最后一条回复
        return newResponses;
      });
    }, 500);
  }
  //点击转人工
  const handlelabor = () => {
    setIsTransferring(!isTransferring)
  }
  //滚动
  useEffect(() => {
    scrollToBottom()
  })
  //接受消息
  useEffect(() => {
    socketRef.current = io('http://localhost:8080');

    socketRef.current.on('connect', () => {
      console.log('Socket.IO 连接已建立');
    });
    //心跳优化
    socketRef.current.on('heartbeat', (msg: string) => {
      console.log('心跳消息:', msg);
    });

    socketRef.current.on('response', (data: string) => {
      console.log('收到消息:', data);
      const currentTime = new Date(Date.now()).toLocaleString();
      setTimeout(() => {
        setApply((prev) => [
          ...prev,
          {
            time: currentTime,
            apply: data, // 这里是客服的回复
          },
        ]);
      }, 1000);
    });

    return () => {
      socketRef.current?.disconnect(); // 清理连接
    };
  }, []); // 只在组件挂载时执行
  const renderMessageWithEmojis = (message: string) => {
    const parts = message.split(/(\[.*?\])/); // 表情文本与普通文本分开，同时保留表情文本
    return parts.map((part: any, index: number) => {
      if (emojiMap[part]) {
        return <i key={index} className={emojiMap[part]}></i>; // 如果是表情，返回对应的<i>标签
      }
      return part; // 否则，返回原始文本
    });
  };
  //发送按钮
  const handleSend = () => {
    if (isTransferring && message !== '') {
      const currentTime = new Date(Date.now()).toLocaleString();
      // 使用 renderMessageWithEmojis 函数处理消息
      const processedMessage = renderMessageWithEmojis(message);
      setResponse((prev) => [
        ...prev,
        {
          time: currentTime,
          user: processedMessage,
        },
      ]);

      socketRef.current?.emit('message', message)
      setMessage('');
      scrollToBottom();
    } else {
      alert('联系人工或输入内容不能为空');
    }
  };
  //上传图片

  const handleChange = (info: any) => {
    console.log(info);

    const currentTime = new Date(Date.now()).toLocaleString();

    // 直接处理 info.file
    if (info.file.status === 'done') { // 确保文件上传完成
      const imageUrl = URL.createObjectURL(info.file.originFileObj); // 创建临时 URL
      setResponse(prev => [
        ...prev,
        { user: <img src={imageUrl} alt="用户上传" style={{ maxWidth: '100px' }} />, time: currentTime }
      ]);
      socketRef.current?.emit('message', imageUrl)
    }
  };

  const props: UploadProps = {
    beforeUpload: (file) => {
      const isPNG = file.type === 'image/png' || file.type === 'image/jpeg'; // 注意这里有个修复
      if (!isPNG) {
        message.error(`${file.name} is not a png/jpg file`);
      }
      return isPNG || Upload.LIST_IGNORE;
    },
    onChange: handleChange,
  };

  //表情
  const emojiMap = {
    "[微笑]": "emojine",
    "[伤心]": "emojine1",
    "[美女]": "emojine2",
    "[发呆]": "emojine3",
    "[墨镜]": "emojine4",
    "[流泪]": 'emojine5',
    "[羞]": 'emojine6',
    "[哑]": "emojine7",
    "[睡]": "emojine8",
    "[哭]": "emojine9",
    "[尴尬]": "emojine10",
    "[怒]": "emojine11",
    "[调皮]": "emojine12",
    "[笑]": "emojine13",
    "[惊讶]": "emojine14",
    "[难过]": "emojine15",
    "[酷]": "emojine16",
    "[囧]": "emojine17",
    "[抓狂]": "emojine18",
    "[吐]": "emojine19",
    "[偷笑]": "emojine20",
  };

  //表情
  const [open, setOpen] = useState(false);

  const handleEmjoy = (e: any) => {
    setOpen(true);
    const emojiValue = e.currentTarget.getAttribute('data-value');
    if (emojiValue) {
      // 将表情文本添加到输入框
      setMessage(prev => prev + emojiValue);
    }
    hide()

  }

  const hide = () => {
    setOpen(false);
  };
  return (
    <div className={`${style.chat}`}>
      <div className={style.top}>
        <div className={style.top1}>
          <img src={chat} alt="" style={{ width: '40px', height: '40px', borderRadius: '50%' }} />
          <h3>创可贴机器人客服小助手</h3>
        </div>
        <span onClick={handlereturn}>
          <MinusOutlined />
        </span>
      </div>
      <div className={style.center} ref={messagesRef}>
        <div className={style.quest}>
          <div>
            <div className={style.questname}>
              创可贴机器人客服小助手{time}
            </div>
            <div>
              <h3>常见问题</h3>
              <Collapse accordion items={items} className={style.collapse}
              />
            </div>
          </div>
        </div>
        <div className={style.apply} ref={messagesRef}>
          {response.map((item, index) => (
            <div key={index} className={style.dialogPair}>
              <div className={style.you}>
                <div className={style.questname}>
                  小爱同学 {item.time}
                </div>
                <div className={style.applycontant}>
                  {item.user}
                </div>
              </div>
              {/* 左边回复 */}
              <div className={style.zuo}>
                <div className={style.questname}>
                  创可贴机器人客服小助手 {apply[index]?.time}
                </div>
                <div className={style.applycontant}>
                  {apply[index]?.apply}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className={style.send}>
        <div style={{ textAlign: 'center', color: '#ccc', height: "30px", lineHeight: '30px' }}>
          {
            isTransferring ? "欢迎来到人工服务" : ''
          }
        </div>
        <div className={style.people}>
          {
            isTransferring ?
              <div className={style.icon1}>
                <Popover
                  // open={open}
                  onOpenChange={handleEmjoy}
                  content={
                    <div className="emojiPane">
                      <a data-value="[微笑]" onClick={handleEmjoy}><i className="emojine"></i></a>
                      <a data-value="[伤心]" onClick={handleEmjoy}><i className="emojine1"></i></a>
                      <a data-value="[美女]" onClick={handleEmjoy}><i className='emojine2'></i></a>
                      <a data-value="[发呆]" onClick={handleEmjoy}><i className='emojine3'></i></a>
                      <a data-value="[墨镜]" onClick={handleEmjoy}><i className='emojine4'></i></a>
                      <a data-value="[流泪]" onClick={handleEmjoy}><i className='emojine5'></i></a>
                      <a data-value="[羞]" onClick={handleEmjoy}><i className='emojine6'></i></a>
                      <a data-value="[哑]" onClick={handleEmjoy}><i className='emojine7'></i></a>
                      <a data-value="[睡]" onClick={handleEmjoy}><i className='emojine8'></i></a>
                      <a data-value="[哭]" onClick={handleEmjoy}><i className='emojine9'></i></a>
                      <a data-value="[尴尬]" onClick={handleEmjoy}><i className='emojine10'></i></a>
                      <a data-value="[怒]" onClick={handleEmjoy}><i className='emojine11'></i></a>
                      <a data-value="[调皮]" onClick={handleEmjoy}><i className='emojine12'></i></a>
                      <a data-value="[笑]" onClick={handleEmjoy}><i className='emojine13'></i></a>
                      <a data-value="[惊讶]" onClick={handleEmjoy}><i className='emojine14'></i></a>
                      <a data-value="[难过]" onClick={handleEmjoy}><i className='emojine15'></i></a>
                      <a data-value="[酷]" onClick={handleEmjoy}><i className='emojine16'></i></a>
                      <a data-value="[囧]" onClick={handleEmjoy}><i className='emojine17'></i></a>
                      <a data-value="[抓狂]" onClick={handleEmjoy}><i className='emojine18'></i></a>
                      <a data-value="[吐]" onClick={handleEmjoy}><i className='emojine19'></i></a>
                      <a data-value="[偷笑]" onClick={handleEmjoy}><i className='emojine20'></i></a>

                    </div>
                  }
                  trigger="click"
                >
                  <SmileOutlined />
                </Popover>
                <ImgCrop rotationSlider>
                  <Upload {...props}
                    action="http://localhost:9000/api/upload"
                    showUploadList={false}
                    onChange={handleChange} // 处理文件变化
                  >
                    <FolderAddOutlined />
                  </Upload>
                </ImgCrop><ScissorOutlined /><LikeOutlined />
              </div>
              :
              <LikeOutlined />
          }
          <div style={{ cursor: "pointer" }} onClick={handlelabor}>
            转人工</div>
        </div>
        <textarea placeholder="很高兴为您服务，请描述您的问题" value={message}
          onChange={(e) => setMessage(e.target.value)}
        />
        <button className={style.btn} onClick={handleSend}>发送</button>
      </div>
    </div>
  )
}

export default Index
